package cn.congzhou.crm.web.controller;


import cn.congzhou.crm.domain.Department;
import cn.congzhou.crm.domain.Employee;
import cn.congzhou.crm.domain.School;
import cn.congzhou.crm.query.EmployeeQueryObject;
import cn.congzhou.crm.service.IDepartmentService;
import cn.congzhou.crm.service.IEmployeeService;
import cn.congzhou.crm.service.IRoleService;
import cn.congzhou.crm.service.ISchoolService;
import cn.congzhou.crm.utils.ResultJSON;
import cn.congzhou.crm.utils.UserContext;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    private Logger logger = LoggerFactory.getLogger(EmployeeController.class);

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private ISchoolService schoolService;


//   显示页面，首页
    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") EmployeeQueryObject qo, Model model) {
        model.addAttribute("ro", employeeService.selectByPage(qo));
        model.addAttribute("depts",departmentService.selectAll());

        return "/employee/list";
    }


    @RequestMapping("/input")
    @RequiresPermissions(value = {"编辑员工信息","employee:input"},logical = Logical.OR)
    public String input(Long id, Model model) {
        if (id != null) {
            model.addAttribute("entity", employeeService.selectByPrimaryKey(id));
        }
        model.addAttribute("depts",departmentService.selectAll());
        model.addAttribute("roles",roleService.selectAll());
        return "/employee/input";
    }

    /*@RequestMapping("/saveOrUpdate")
    @RequiresPermissions({"添加/保存员工信息","employee:saveOrUpdate"})
    public String saveOrUpdate(Employee emp,Long[] ids) {
        employeeService.saveOrUpdate(emp,ids);

        return "redirect:/employee/list.do";
    }*/

//    批量删除
    @RequestMapping("/batchdelete")
    @RequiresPermissions(value = {"批量删除员工","employee:batchdelete"},logical = Logical.OR)
    @ResponseBody
    public Object batchDelete(Long[] ids){
        ResultJSON result = new ResultJSON();
        try {
            employeeService.batchDelete(ids);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("批量删除失败");
        }

        return result;
    }

    @RequestMapping("/delete")
    @RequiresPermissions(value = {"删除员工","employee:delete"},logical = Logical.OR)
    @ResponseBody
    public Object delete(Long id) {
        ResultJSON result = new ResultJSON();
        try {
            employeeService.deleteByPrimaryKey(id);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("删除失败");
        }

        return result;
    }


    //员工数据导出
    @RequestMapping("/export")
    public ModelAndView exportExcel(HttpServletResponse response) {
        //查询数据库获取要输出的内容
        List<Employee> employees = employeeService.selectAll();
        //创建工作簿
        HSSFWorkbook book = new HSSFWorkbook();
        //创建纸
        HSSFSheet sheet = book.createSheet("员工信息表");
        //创建行
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("电话");
        row.createCell(2).setCellValue("年龄");
//      使用循环将查到的数据写到工作簿中
        for (int i=0; i<employees.size();i++){
            //创建一个新的行
            HSSFRow rowi = sheet.createRow(i + 1);
            //创建单元格，往里面添加数据
            rowi.createCell(0).setCellValue(employees.get(i).getName());
            rowi.createCell(1).setCellValue(employees.get(i).getPhone());
            rowi.createCell(2).setCellValue(employees.get(i).getAge());
        }
        //指定输出的文件名
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        try {
            book.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/import")
    public String employeeImport(MultipartFile xls) throws IOException {
        //解析上传文件的流创建工作簿对象
        HSSFWorkbook book = new HSSFWorkbook(xls.getInputStream());
        //获取第一张表的名字
        String sheetName = book.getSheetName(0);
        //获取第一张表的内容
        HSSFSheet sheet = book.getSheet(sheetName);
        //循环遍历表的每一行数据，保存到数据库中
        for(int i = 0; i< sheet.getLastRowNum(); i++){
            //获取每个单元格的数据
            HSSFRow row = sheet.getRow(i + 1);
            String name = row.getCell(0).getStringCellValue();
            String phoneStr = row.getCell(1).toString();
            Double doubleAge = row.getCell(2).getNumericCellValue();
            int age = doubleAge.intValue();
            //将单元格的数据设置到对象中
            Employee emp = new Employee();
            emp.setName(name);
            emp.setPassword(name);
            emp.setPhone(phoneStr);
            emp.setAge(age);
            emp.setDept(new Department(1L,null,null,null
            ));
            //保存到数据库
            employeeService.saveOrUpdate(emp,null);
        }
        return "redirect:/employee/list.do";
    }


    //===================================一下是添加ligerUI添加的方法=================================================================//

    @RequestMapping(value = "/toEmployeeGrid",method = RequestMethod.GET)
    @RequiresPermissions(value = {"查询员工信息","employee:query"},logical = Logical.OR)
    public String toEmployeeGrid(Model model){
        List<School> schools = schoolService.selectAll();
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("schools",JSON.toJSONStringWithDateFormat(schools,"yyyy-MM-dd"));
        model.addAttribute("depts",JSON.toJSONStringWithDateFormat(departments,"yyyy-MM-dd"));
        return "/employee/employeeGrid";
    }

    @RequestMapping(value = "/getEmployeeData",method = RequestMethod.POST)
    @RequiresPermissions(value = {"查询员工信息","employee:query"},logical = Logical.OR)
    public void getEmployeeData(@ModelAttribute("qo") EmployeeQueryObject qo,HttpServletResponse response){
        PageInfo<Employee> pageInfo = employeeService.selectByPage(qo);
        String json = JSON.toJSONStringWithDateFormat(pageInfo, "yyyy-MM-dd");
        PrintWriter writer = null;
        try{
            writer = response.getWriter();
            writer.println(json);
            writer.flush();
            logger.info(UserContext.getCurrentLoginUserAndIp() + "查询员工信息");
        }catch (Exception e){
            logger.error("查询员工信息出错",e);
        }finally {
            if(writer != null){
                try{
                    writer.close();
                }catch (Exception e){ }
            }
        }
    }


    @RequestMapping(value = "/toInputEmployee",method = RequestMethod.GET)
    @RequiresPermissions(value = {"新增/修改员工信息","employee:saveOrUpdate"},logical = Logical.OR)
    public String toInputEmployee(Long id,Model model){
        if (id != null) {
            model.addAttribute("emp", employeeService.selectByPrimaryKey(id));
        }
        List<School> schools = schoolService.selectAll();
        model.addAttribute("schoolsJson",JSON.toJSONString(schools));
        model.addAttribute("schools",schools);
        model.addAttribute("roles",roleService.selectAll());
        return "/employee/employeeEdit";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequiresPermissions({"添加/编辑员工信息","employee:saveOrUpdate"})
    public Object saveOrUpdate(Employee emp,Long[] ids) {
        ResultJSON result = new ResultJSON();
        try{
            employeeService.saveOrUpdate(emp,ids);
            logger.info(UserContext.getCurrentLoginUserAndIp() + "添加/修改了员工" + emp.getSid() + "的信息");
        }catch (Exception e){
            result.mark("保存失败" + e.getMessage());
            logger.error("保存员工信息出错",e);
        }
        return result;
    }


}
